layui.use(['jquery', 'laytpl', 'form', 'laydate', 'exutil', 'extable', 'exconfig',
], function () {
    var $ = layui.$;
    var form = layui.form;
    var laydate = layui.laydate;
    var exutil = layui.exutil;
    var extable = layui.extable;
    var exconfig = layui.exconfig;


    var table = {
        tag: 'table',
        tableCurrentPage: 1,
        //初始化
        init: function () {
            var that = this;
            //时间
            this.initDate();
            //渲染
            this.renderTable();
            //搜索按钮
            form.on('submit(searchBtn)', function (data) {
                exutil.updateTabTable(that.tag, null, 1, data.field);
                return false;
            });
            //表格：工具栏
            extable.on(`toolbar(${this.tag})`, function (obj) {
                switch (obj.event) {
                    case 'add'://新增
                        var sourceType = exutil.getCurrentPageType();
                        var url = exconfig.baseUrl() + '/modules/accessManage/pages/blackCar/detail.html';
                        var content = exutil.createUrlForCleanCache(url, {
                            "sourceType": sourceType,
                            "callBack": 'onAddByCallback',
                            "isSelectAll": 'all'
                        });
                        exutil.open({
                            title: "新增",
                            area: ['1200px', '562px'],
                            btn: ['提交', '重置'],
                            content: content//详情页面地址
                        });
                        break;
                    case 'del'://批量删除
                        var checkStatus = extable.checkStatus(that.tag)
                        that.onDelete(checkStatus.data)
                        break;
                    case 'export'://导出
                        var data = form.val('filterForm');
                        data.token = exutil.getCookie(exconfig.tokenKey);
                        data = $.param(data);
                        var url = exconfig.baseUrl() + '/api/info/news/flow/exportExcel?' + data
                        window.open(url);
                        // window.open(encodeURI(url));
                        break;
                }
                return false;
            })
            //表格：操作列
            extable.on(`tool(${this.tag})`, function (obj) {
                var data = obj.data;
                var layEvent = obj.event;
                if (layEvent == "view") {
                    var url = `/modules/app/pages/eXinSheng/flow/detail/detail.html?appCode=${data.wfAppCode}&procId=${data.wfProcID}&status=3&showLike=1`;
                    console.log(data, url)
                    exutil.openNewPage(url);
                    // window.location.href = `.three/w.html?cateId=${data.cateId}&newsId=${data.newsId}`;//跳转二级
                } else if (layEvent == "delete") {
                    that.onDelete([data])
                }
            });
            //表格：点击标题跳转详情
            $(`body`).on('click', '.item-link', function () {
                var event = $(this).data('event')
                $(this).closest('td').siblings().last().find(`a[lay-event="${event}"]`).click()
            })
            /* 刷新表格 使用
                exutil.toast("操作成功", null, function () {
                    window.opener.updateTable();
                    window.close();
                });

                兼容写法，缺点：不可用this.tag,需要将写死
                indow.updateTable = this.updateTable
            */
            window.updateTable = () => {
                exutil.updateTabTable(this.tag);
            }
            //返回按钮
            $('.back-btn').on('click', function () {
                window.history.back();
            })
        },
        //初始化：时间方法
        initDate: function () {
            laydate.render({
                elem: '#date',
                type: 'datetime',
                range: true,
                ready: function (date) {
                    $(".layui-laydate-footer [lay-type='datetime'].laydate-btns-time").click();
                    $(".laydate-main-list-1 .layui-laydate-content li ol li:last-child").click();
                    $(".layui-laydate-footer [lay-type='date'].laydate-btns-time").click();
                },
                done: function (value, date, endDate) {
                    if (value == '') {
                        $('#endDate').val('')
                        $('#startDate').val('')
                    } else {
                        value = value.split(' - ')
                        $('#startDate').val(value[0])
                        $('#endDate').val(value[1])
                    }
                },

            });
        },
        //渲染表格
        renderTable: function () {
            console.log('渲染时tag', this.tag)
            extable.render({
                elem: "#" + this.tag,
                url: "/api/info/news/flow/page",
                // height: 'auto',
                id: this.tag,
                page: true,
                loading: true,
                toolbar: "#toolbar",
                where: {
                    title: $("#titleByAppraise").val(),
                },
                defaultToolbar: ["filter"],
                cols: [
                    [
                        /**
                         * 常用列宽
                         *    时间：170
                         *  姓名：100
                         *    两个字：60
                         */
                        //{type: 'checkbox', fixed: 'left'},
                        {type: "numbers", width: 65, title: "序号",},
                        {field: "ip", title: "访问者IP", width: 150,},
                        {field: "cateName", title: "栏目名称", width: 150,},
                        {
                            field: "newsTitle",
                            title: "文章标题",
                            minWidth: 250,
                            templet: function (d) {
                                //data-event="view"，为lay-event="view"，根据需要调整
                                return `<div class="item-link" data-event="view">${d.title}<div>`
                            }
                        },
                        {field: "createDate", title: "访问时间", width: 170},
                        {field: "url", title: "访问地址", width: 250},
                        {
                            field: "isVote",
                            title: "是否投票",
                            width: 90,
                            templet: function (d) {
                                var txt = "待提交";
                                switch (d.isVote) {
                                    case 1: {
                                        txt = "已提交";
                                        break;
                                    }
                                }
                                return txt;
                            },
                        },
                        //{ title: "操作", toolbar: "#rowbar", width: 130, fixed: "right", align: "center", },
                    ],
                ],
                exdone: function (res, curr, count) {
                    // 设置当前页码
                    this.tableCurrentPage = curr;
                },
            });
        },
        //事件-删除
        onDelete: function (list) {
            var that = this
            const tips = list.map(v => v.personnelName).join();
            const ids = list.map(v => v.id).join();
            if (ids == '') {
                exutil.msg("请选择数据，再进行删除");
                return
            }
            exutil.confirm('确定<b class="red">' + tips + '</b>删除吗？', function (index) {
                var opts = {
                    data: {
                        ids: ids
                    }
                }
                exutil.post('/api/black/user/delete', opts).then(function (res) {
                    exutil.toast("操作成功");
                    exutil.updateTabTable(that.tag);
                    exutil.close();
                });
            });

        },
    };
    table.init();
});
